package middleware

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"usershop/api/internal/types"
	"usershop/api/pkg"
)

type AuthTokenMiddleware struct {
}

func NewAuthTokenMiddleware() *AuthTokenMiddleware {
	return &AuthTokenMiddleware{}
}

func (m *AuthTokenMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		fmt.Println("触发中间件............")
		token := r.Header.Get("token")
		fmt.Println(token)

		if token == "" {
			resp := &types.ResMsg{
				Cre:  -1,
				Msg:  "token 为空",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		//验证token是否有效

		payload, err := pkg.ParserJwtToken(token)
		if err != nil {
			resp := &types.ResMsg{
				Cre:  -1,
				Msg:  err.Error(),
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		fmt.Println(payload)

		value := context.WithValue(r.Context(), "UserID", payload)

		next(w, r.WithContext(value))
	}
}
